using AutoMapper;
using B.S.XZYData.Api.Read.Application.Command.Plan;
using B.S.XZYData.Api.Read.Dto.Plan;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.Plan
{
    /// <summary>
    /// 获取生产计划明细列表处理器
    /// </summary>
    public class GetPlanItemsHandler : IRequestHandler<GetPlanItemsCommand, ApiResult<List<PlanItemDto>>>
    {
        private readonly IBaseRepository<PlanItemModel> _planItemRepo;
        private readonly IMapper _mapper;

        public GetPlanItemsHandler(
            IBaseRepository<PlanItemModel> planItemRepo,
            IMapper mapper)
        {
            _planItemRepo = planItemRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<PlanItemDto>>> Handle(GetPlanItemsCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<List<PlanItemDto>>();

            try
            {
                // 获取计划明细列表
                var planItems = _planItemRepo.GetAll()
                    .Where(x => x.PlanId == request.PlanId)
                    .OrderBy(x => x.Id)
                    .ToList();

                // 映射到DTO
                var planItemDtos = _mapper.Map<List<PlanItemDto>>(planItems);

                res.Data = planItemDtos;
                res.Code = ApiEnum.Success;
                res.Msg = "获取计划明细列表成功";
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"获取计划明细列表失败：{ex.Message}";
            }

            return res;
        }
    }
} 